import React from "react"
import { Space, Tag } from "antd"
import { useSelector,useDispatch } from "react-redux"
import { closeTag,setMenuList } from "../../store/reducers/tab"
import  {useLocation,useNavigate} from "react-router-dom"

import "./index.css"
const CommonTag = ()=>{
    //获取store中tablist数据
   
    const tabsList = useSelector ( state =>state.tab.tabList)
    const currentMenu = useSelector ( state =>state.tab.currentMenu)
    const dispatch = useDispatch()
    //获取当前路径
    const location = useLocation()
    //路由的跳转
    const navigate = useNavigate()
    const handleClose = (item,index)=>{
        console.log(tabsList)
        dispatch(closeTag(item))
        let length = tabsList.length - 1
      
        if(item.path !==location.pathname){
            //如果关闭的不是当前的tag
            return

        }
        if(index === length){
            //如果关闭的是最后一个标签
            //跳转到前一个标签
            const curData = tabsList[length-1]
            dispatch(setMenuList(curData))
            navigate(curData.path)
            
        }else{
            //如果关闭的不是最后一个标签,并且选中该标签，就跳转到下一个标签
            if(tabsList.length > 1){
                const nextData = tabsList[index+1]
                dispatch(setMenuList(nextData))
                navigate(nextData.path)
            }
        }

        

        
    }
    //点击非高亮标签的逻辑
    const handleChange = (item)=>{
        console.log(item,111)
        dispatch(setMenuList(item))
        navigate(item.path)
       
       
    }
    //tag显示的逻辑
    const setTag = (flag,item,index)=>{
        return (
            flag? 
            <Tag key={item.name} color="#55acee" closeIcon onClose={()=>handleClose(item,index)} >{item.label}</Tag>
            :
            // 如果不是选中的就显示灰色的tag
            <Tag key={item.name} closeIcon onClose={()=>handleClose(item,index)}  onClick={()=>handleChange(item)}>{item.label}</Tag>
        )

    }


    


    return (
        <Space size={[0,8]} wrap className="common-tag">
      
            {
                currentMenu.name && tabsList.map((item,index)=> (setTag(item.path === currentMenu.path,item,index))
                //如果当前选中的和已有的路径相同

                ) 

            }

        </Space>
        
    )
}
export default CommonTag